package user

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gconv"
	"goAdminV1/api/user/v1"
	"goAdminV1/internal/middleware"
	"goAdminV1/internal/model"
)

func (c *ControllerV1) UserOnline(ctx context.Context, req *v1.UserOnlineReq) (res *v1.UserOnlineRes, err error) {
	res = &v1.UserOnlineRes{}

	// 获取用户ID
	userIDValue := ctx.Value(middleware.ContextUserIDKey)
	userID, ok := userIDValue.(uint)
	if !ok {
		return nil, gerror.New("从上下文中获取的用户 ID 类型错误")
	}

	// 调用 model 层获取用户信息
	userData, permissions, err := model.GetUserOnlineByID(ctx, userID)
	if err != nil {
		return nil, err
	}

	// 构建响应
	res.ID = gconv.Int(userData.Id)
	res.Username = gconv.String(userData.Username)
	res.Password = gconv.String(userData.Password)
	res.Email = gconv.String(userData.Email)
	res.Avatar = gconv.String(userData.Avatar)
	res.RememberToken = gconv.String(userData.RememberToken)
	res.DepartmentID = gconv.Int(userData.DepartmentId)
	res.CreatorID = gconv.Int(userData.CreatorId)
	res.Status = gconv.Int(userData.Status)
	res.LoginIP = gconv.String(userData.LoginIp)
	res.LoginAt = gconv.Int(userData.LoginAt)
	res.CreatedAt = gconv.String(userData.CreatedAt)
	res.UpdatedAt = gconv.String(userData.UpdatedAt)
	res.Permissions = permissions
	res.Roles = []interface{}{} // 保留空数组
	res.Jobs = []interface{}{}  // 保留空数组
	return res, nil
}
